﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UPos.Core.DataDriver;

namespace UPos.Core.LogProvider
{
    public class LogSQLite
    {
        static DbSQLite db = new DbSQLite();

        public static event Action<string, string, DateTime> Writed;

        static void Write(string message, string result, DateTime time)
        {
            try
            {
                using (var cmd = db.CreateCommand("insert into logs values(@time, @message, @result)"))
                {
                    cmd.Parameters.AddWithValue("@time", time);
                    cmd.Parameters.AddWithValue("@message", message);
                    cmd.Parameters.AddWithValue("@result", result);
                    cmd.ExecuteNonQuery();
                }
                OnWrited(message, result, time);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void Write(string message, string result, params object[] args)
        {
            Write(message, string.Format(result, args), DateTime.Now);
        }

        static void OnWrited(string message, string result, DateTime time)
        {
            if (Writed != null)
                Writed(message, result, time);
        }

        public static DataTable Get()
        {
            using (SQLiteDataAdapter a = new SQLiteDataAdapter(db.CreateCommand("select * from Logs order by Time")))
            {
                DataTable t = new DataTable();
                a.Fill(t);
                return t;
            }
        }
    }
}
